package comp

import (
	"bytes"
)

// StringBuilder 类型，用于高效地构建和操作字符串
type StringBuilder struct {
	buffer bytes.Buffer // 内部缓冲区
}

// 创建一个带初始容量的 StringBuilder
func NewStringBuilderCap(capnum int) *StringBuilder {
	builder := StringBuilder{
		buffer: *bytes.NewBuffer(make([]byte, 0, capnum)),
	}
	return &builder
}

// 创建一个新的 StringBuilder
func NewStringBuilder() *StringBuilder {
	var builder StringBuilder
	return &builder
}

// 创建一个新的 StringBuilder，并初始化为指定字符串
func NewStringBuilderString(str *String) *StringBuilder {
	var builder StringBuilder
	builder.buffer.WriteString(str.ToString())
	return &builder
}

// 追加字符串并换行
func (builder *StringBuilder) Appendln(s string) *StringBuilder {
	builder.buffer.WriteString(s + "\n")
	return builder
}

// 追加字符串
func (builder *StringBuilder) Append(s string) *StringBuilder {
	builder.buffer.WriteString(s)
	return builder
}

// 追加单个字符
func (builder *StringBuilder) AppendRune(s rune) *StringBuilder {
	builder.buffer.WriteRune(s)
	return builder
}

// 追加多个字符串
func (builder *StringBuilder) AppendStrings(ss ...string) *StringBuilder {
	for i := range ss {
		builder.buffer.WriteString(ss[i])
	}
	return builder
}

// 追加整数
func (builder *StringBuilder) AppendInt(i int) *StringBuilder {
	builder.buffer.WriteString(NewStringInt(i).ToString())
	return builder
}

// 追加 int64 类型的整数
func (builder *StringBuilder) AppendInt64(i int64) *StringBuilder {
	builder.buffer.WriteString(NewStringInt64(i).ToString())
	return builder
}

// 追加 float64 类型的浮点数
func (builder *StringBuilder) AppendFloat64(f float64) *StringBuilder {
	builder.buffer.WriteString(NewStringFloat64(f).ToString())
	return builder
}

// 替换字符串中的指定内容
func (builder *StringBuilder) Replace(old, new string) *StringBuilder {
	str := NewString(builder.ToString()).Replace(old, new)
	builder.Clear()
	builder.buffer.WriteString(str.ToString())
	return builder
}

// 删除最后一个字符
func (builder *StringBuilder) RemoveLast() *StringBuilder {
	str1 := NewString(builder.ToString())
	builder.Clear()
	str2 := str1.Substring(0, str1.Len()-1)
	builder.buffer.WriteString(str2.ToString())
	return builder
}

// 清空 StringBuilder
func (builder *StringBuilder) Clear() *StringBuilder {
	builder.buffer.Reset()
	return builder
}

// 将 StringBuilder 转换为字符串
func (builder *StringBuilder) ToString() string {
	return builder.buffer.String()
}

// 判断 StringBuilder 是否为空
func (builder *StringBuilder) IsEmpty() bool {
	return builder.buffer.Len() == 0
}
